package com.taglab.chic.search.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.annotation.Resource;

import com.taglab.chic.search.SearchService;
import com.taglab.chic.search.Query;
import com.taglab.chic.search.SearchResults;

/**
 * @author Markus Kobler
 */
public class SpringSearchController extends AbstractController {

  private final static Logger logger = LoggerFactory.getLogger(SpringSearchController.class);

  private SearchService searchService;
  private QueryRequestParser queryRequestParser = new QueryRequestParser();
  
  private String viewName = "search";

  private String resultsKey = "searchResults";

  @Resource
  public void setSearchService(SearchService searchService) {
    this.searchService = searchService;
  }

  public void setSearchTermsParam(String searchTermsParam) {
    queryRequestParser.setSearchTermsParam(searchTermsParam);
  }

  public void setStartPageParam(String startPageParam) {
    queryRequestParser.setStartPageParam(startPageParam);
  }

  public void setItemsPerPageParam(String itemsPerPageParam) {
    queryRequestParser.setItemsPerPageParam(itemsPerPageParam);
  }

  public void setLocalized(boolean localized) {
    queryRequestParser.setLocalized(localized);
  }

  public void setDefaultItemsPerPage(int defaultItemsPerPage) {
    queryRequestParser.setDefaultItemsPerPage(defaultItemsPerPage);
  }

  public String getViewName() {
    return viewName;
  }

  public void setViewName(String viewName) {
    this.viewName = viewName;
  }

  public String getResultsKey() {
    return resultsKey;
  }

  public void setResultsKey(String resultsKey) {
    this.resultsKey = resultsKey;
  }

  protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

    Query query = queryRequestParser.parse(request);
    
    logger.debug("search query {}", query);

    SearchResults results = searchService.search(query);

    logger.debug("{} returned {}", query, results);

    return new ModelAndView(getViewName(), getResultsKey(), results);
  }
}
